package com.zmn.plat.business.impl.category;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.zmn.plat.common.util.SimpleSpellUtil;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.StatusDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.InitialUtil;
import com.zmn.plat.business.interfaces.category.BaseCategoryBService;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.common.dto.category.CategoryDRO;
import com.zmn.plat.common.dto.category.CategoryPageDIO;
import com.zmn.plat.common.dto.category.CategoryPageDRO;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.category.BaseCategoryQuery;
import com.zmn.plat.model.entity.product.ServProduct;
import com.zmn.plat.model.entity.product.ServProductQuery;
import com.zmn.plat.services.interfaces.category.BaseCategoryService;
import com.zmn.plat.services.interfaces.product.ServProductService;

/**
 * @author linfeng
 * @version v1.0
 * @类说明：产品分类管理级联停用serviceImpl
 * @since 2019/09/25 20:52
 */
@Service
public class BaseCategoryBServiceImpl implements BaseCategoryBService {
    @Resource
    BaseCategoryService baseCategoryService;

    @Resource
    ServProductService servProductService;

    @Override
    public CategoryDRO findShowCategoryByCategId(Integer categId) {
        BaseCategory category = baseCategoryService.findShowCategoryByCategId(categId);
        if (category == null) {
            return null;
        }
        BeanCopier copier = BeanCopier.create(BaseCategory.class, CategoryDRO.class, false);
        CategoryDRO dro = new CategoryDRO();
        copier.copy(category, dro, null);
        return dro;
    }

    @Override
    public CategoryPageDRO listPageByQuery(CategoryPageDIO query) {
        BaseCategoryQuery categoryQuery = new BaseCategoryQuery();
        categoryQuery.setShowType(query.getShowType());
        categoryQuery.setLevel(query.getLevel());
        // 计价器第一步根据计价器前台二级分类计价器名称查询
        categoryQuery.setTariffName(query.getName());
        if (query.getPageNum() != null && query.getPageNum() > 0) {
            categoryQuery.setPageIndex(query.getPageNum());
        }
        if (query.getPageSize() != null && query.getPageSize() > 0) {
            categoryQuery.setPageSize(query.getPageSize());
        }
        List<BaseCategory> categs = baseCategoryService.listPageByFaultQuery(categoryQuery);
        List<CategoryDRO> items = new ArrayList<>();
        BeanCopier copier = BeanCopier.create(BaseCategory.class, CategoryDRO.class, false);
        for (BaseCategory categ : categs) {
            CategoryDRO dro = new CategoryDRO();
            copier.copy(categ, dro, null);
            items.add(dro);
        }
        CategoryPageDRO dro = new CategoryPageDRO();
        dro.setCategoryList(items);
        dro.setTotalCount(categoryQuery.getTotalCount());
        return dro;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatusByCategoryOne(List<Integer> arrayIds, int status, String mcStaffName) {
        baseCategoryService.updateStatusBatch(arrayIds, status, mcStaffName);

        for (Integer id : arrayIds) {
            List<BaseCategory> categoryTwoList = baseCategoryService.listByParentIdForShow(id, GlobalDict.STATUS_ENABLE);
            List<Integer> categoryTwoIds = categoryTwoList.stream().map(BaseCategory::getCategId).collect(Collectors.toList());
            if (categoryTwoIds.size() != 0) {
                baseCategoryService.updateStatusBatch(categoryTwoIds, status, mcStaffName);
            }
        }

        // 根据一级分类id查询启用的前台产品
        ServProductQuery servProductQuery = new ServProductQuery();
        servProductQuery.setStatus(GlobalDict.STATUS_ENABLE);
        servProductQuery.setShowType(ProductConsts.EC_PRODUCT_TYPE);
        servProductQuery.setCategOneIds(arrayIds);
        List<ServProduct> servProductList = servProductService.listByQuery(servProductQuery);
        List<Integer> serProductIds = servProductList.stream().map(ServProduct::getProductId).collect(Collectors.toList());
        if (serProductIds.size() != 0) {
            StatusDTO dto = new StatusDTO();
            dto.setIds(serProductIds);
            dto.setStatus(status);
            dto.setUpdater(mcStaffName);
            dto.setUpdateTime(new Date());
            servProductService.updateStatusBatch(dto);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatusByCategoryTwo(List<Integer> arrayIds, int status, String mcStaffName) {
        baseCategoryService.updateStatusBatch(arrayIds, status, mcStaffName);

        // 根据二级分类id查询启用的前台产品
        ServProductQuery servProductQuery = new ServProductQuery();
        servProductQuery.setStatus(GlobalDict.STATUS_ENABLE);
        servProductQuery.setShowType(ProductConsts.EC_PRODUCT_TYPE);
        servProductQuery.setCategIds(arrayIds);
        List<ServProduct> servProductList = servProductService.listByQuery(servProductQuery);
        List<Integer> serProductIds = servProductList.stream().map(ServProduct::getProductId).collect(Collectors.toList());
        if (serProductIds.size() != 0) {
            StatusDTO dto = new StatusDTO();
            dto.setIds(serProductIds);
            dto.setStatus(status);
            dto.setUpdater(mcStaffName);
            dto.setUpdateTime(new Date());
            servProductService.updateStatusBatch(dto);
        }

    }

    @Override
    public Integer updateByKey(BaseCategory baseCategoryVo, String operator) {
        BaseCategory result = baseCategoryService.findByKey(baseCategoryVo.getCategId());
        if (result == null) {
            throw new PlatException("产品分类不存在");
        }
        checkTariffName(result.getCategId(), baseCategoryVo.getTariffName(), result.getLevel(), result.getShowType());
        result.setName(baseCategoryVo.getName());
        result.setUpdater(operator);
        result.setUpdateTime(DateUtil.getNow());
        result.setFirstLetter(InitialUtil.getFristEnName(baseCategoryVo.getName()));
        String spell = SimpleSpellUtil.parseNameToSimpleSpell(baseCategoryVo.getName(),null);
        result.setSimpleSpell(spell);

        result.setTariffName(baseCategoryVo.getTariffName());
        result.setTariffStatus(baseCategoryVo.getTariffStatus());
        result.setIcon(baseCategoryVo.getIcon());
        result.setDetailName(baseCategoryVo.getDetailName());
        result.setSort(baseCategoryVo.getSort());
        // result.setServiceMinutes(baseCategoryVo.getServiceMinutes());
        Integer res = baseCategoryService.updateByKey(result);
        // 禁用计价器级联禁用
        // if (baseCategoryVo.getTariffStatus().equals(GlobalConsts.NO)) {
        // baseCategoryService.updateTariffStatusBatch(Arrays.asList(baseCategoryVo.getCategId()), GlobalConsts.NO, operator,
        // result.getShowType());
        // ServProduct product = new ServProduct();
        // product.setShowType(result.getShowType());
        // product.setTariffStatus(GlobalConsts.NO);
        // if (result.getParentId().equals(GlobalConsts.LEVEL_1)) {
        // product.setCategOneId(result.getCategId());
        // } else {
        // product.setCategId(result.getCategId());
        // }
        // servProductService.updateTariffStatusBatch(product);
        // }
        return res;
    }

    /**
     * 更新
     *
     * @param category
     *            分类
     * @return
     */
    @Override
    public Integer insert(BaseCategory category, String operator) {
        if (category.getParentId() == null || category.getParentId() < 1) {
            category.setParentId(GlobalConsts.TOP_ID);
            category.setLevel(GlobalConsts.LEVEL_1);
        } else {
            category.setLevel(GlobalConsts.LEVEL_2);
        }
        checkTariffName(category.getCategId(), category.getTariffName(), category.getLevel(), category.getShowType());
        category.setCreater(operator);
        category.setCreateTime(DateUtil.getNow());
        category.setUpdater(operator);
        category.setUpdateTime(DateUtil.getNow());
        category.setStatus(GlobalConsts.YES);
        category.setSort(category.getSort() == null ? GlobalConsts.TOP_ID : category.getSort());
        category.setFirstLetter(InitialUtil.getFristEnName(category.getName()));
        String spell = SimpleSpellUtil.parseNameToSimpleSpell(category.getName(),null);
        category.setSimpleSpell(spell);

        return baseCategoryService.insert(category);
    }

    private void checkTariffName(Integer categId, String tariffName, Integer level, Integer showType) {
        BaseCategoryQuery query = new BaseCategoryQuery();
        if (level.equals(GlobalConsts.LEVEL_1)) {
            query.setLevel(query.LEVEL_1);
        } else {
            query.setLevel(query.LEVEL_2);
        }
        query.setTariffName(tariffName);
        query.setShowType(showType);
        List<BaseCategory> list = baseCategoryService.listByQuery(query);
        if (!CollectionUtils.isEmpty(list)) {
            // 新增的情况
            if (categId == null || categId == 0) {
                if (list.size() > 0) {
                    throw new PlatException("同一级的计价器名称不可相同");
                }
            } else {
                if (list.size() > 1) {
                    throw new PlatException("同一级的计价器名称不可相同");
                }
                BaseCategory category = list.get(0);
                if (category.getCategId() != categId) {
                    throw new PlatException("同一级的计价器名称不可相同");
                }
            }
        }
    }
}
